package org.frank.blockchain.p2p.server;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.frank.blockchain.domain.Command;
import org.frank.blockchain.util.Constants;

import java.util.List;

public class CommandDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int index = in.indexOf(0, in.readableBytes(), Constants.END_BYTE);
        boolean hasEndSymbol = index > -1;
        if (hasEndSymbol) {
            byte[] dataBytes = new byte[in.readableBytes()];
            in.readBytes(dataBytes);
            String json = new String(dataBytes, CharsetUtil.UTF_8);
            if (!JSONUtil.isJson(json)) {
                throw new Exception("非json数据");
            }
            Command command = JSONUtil.toBean(json, Command.class);
            out.add(command);
        } else {
            in.resetReaderIndex();
        }
    }
}
